package com.stars.easyms.monitor.shiro;

import com.stars.easyms.base.util.ClassUtil;
import com.stars.easyms.monitor.MonitorRequestHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>className: EasyMsShiroAuthorityExecutor</p>
 * <p>description: Shiro权限管理执行者</p>
 *
 * @author guoguifang
 * @date 2019-11-22 13:44
 * @since 1.4.1
 */
@Slf4j
final class EasyMsShiroAuthorityExecutor {

    private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);

    void doShiroAuthorityManagement() {
        if (!INITIALIZED.compareAndSet(false, true)) {
            return;
        }

        // 如果存在shiro的jar包则处理
        if (ClassUtil.isExist("org.apache.shiro.spring.web.ShiroFilterFactoryBean") &&
                ClassUtil.isExist("org.apache.shiro.web.servlet.AbstractShiroFilter") &&
                ClassUtil.isExist("org.apache.shiro.session.Session")) {
            // 获取所有的实现了ShiroAuthorityFunc接口的类
            Set<ShiroAuthorityFunc> shiroAuthorityFuncSet = new HashSet<>();
            try {
                ServiceLoader<ShiroAuthorityFunc> shiroAuthorityFuncServiceLoader = ServiceLoader.load(ShiroAuthorityFunc.class);
                for (ShiroAuthorityFunc shiroAuthorityFunc : shiroAuthorityFuncServiceLoader) {
                    shiroAuthorityFuncSet.add(shiroAuthorityFunc);
                }

                // 获取所有的实现了EasyMsMonitorRequestHandler接口的类
                ServiceLoader<MonitorRequestHandler> monitorRequestHandlerServiceLoader = ServiceLoader.load(MonitorRequestHandler.class);
                for (MonitorRequestHandler easyMsMonitorRequestHandler : monitorRequestHandlerServiceLoader) {
                    shiroAuthorityFuncSet.add(easyMsMonitorRequestHandler);
                }
            } catch (Exception e) {
                log.error("Initialization ShiroAuthorityFunc failed!", e);
                return;
            }

            // 排序
            List<ShiroAuthorityFunc> shiroAuthorityFuncList = shiroAuthorityFuncSet.stream()
                    .sorted(Comparator.comparingInt(ShiroAuthorityFunc::getShiroAuthorityOrder))
                    .collect(Collectors.toList());

            // 处理
            new EasyMsShiroAuthorityHandler().handle(shiroAuthorityFuncList);
        }
    }

}